import request_util from "../../../utils/request_util";
import im from "../../../services/api/im";
const app = getApp();

Page({
  data: {
    userInfo: {
      nickname: "",
      avatar: "",
      id: "",
    },
    secondUser: {
      nickname: "",
      avatar: "",
      id: "",
    },
    messageList: [],
    inputValue: "",
    receiverId: "",
    page: 1,
    pageSize: 30,
    canLoadMore: true,
    scrollTop: 0,
    isRecording: false, // 是否正在录音
    isVoiceInput: false, // 是否处于语音输入状态
    isCancelAreaVisible: false, // 是否显示取消区域
  },

  onLoad(options) {
    this.setData({ receiverId: options.id });
    this.boundHandleMessage = this.handleMessage.bind(this);
    app.subscribe("message", this.boundHandleMessage);
    // // 初始化录音管理器
    // this.recorderManager = wx.getRecorderManager();
    // this.getChatDetail(options).then(() => {
    //   this.scrollToBottom();
    // });

    // // 监听录音开始事件
    // this.recorderManager.onStart(() => {
    //   this.setData({ isRecording: true });
    //   console.log("录音开始");
    // });

    // // 监听录音停止事件
    // this.recorderManager.onStop((res) => {
    //   this.setData({ isRecording: false });
    //   const tempFilePath = res.tempFilePath; // 获取录音文件路径
    //   this.sendVoiceMessage(tempFilePath); // 发送语音消息
    // });

    // // 监听录音错误事件
    // this.recorderManager.onError((err) => {
    //   console.error("录音失败：", err);
    //   this.setData({ isRecording: false });
    // });
  },

  // 页面卸载时触发
  onUnload: function () {
    app.unsubscribe("message", this.boundHandleMessage);
    im.im.readMessage.data = {
      id: this.data.receiverId,
      lastCreateTime: null,
    };
    request_util.request(im.im.readMessage);
  },

  // 获取聊天详情
  async getChatDetail(options) {
    im.im.getChatList.data = {
      id: options.id,
      lastCreateTime: null,
      page: this.data.page,
      pageSize: this.data.pageSize,
    };

    const res = await request_util.request(im.im.getChatList);
    if (res.isSuccess) {
      const { data } = res;
      this.setData({
        userInfo: {
          nickname: data.nickname,
          avatar: data.avatar,
          id: data.id,
        },
        secondUser: {
          nickname: data.seNickname,
          avatar: data.seAvatar,
          id: data.seId,
        },
      });

      const formattedMessages = this.formatMessageList(data.chatList);
      this.setData({
        messageList: [...formattedMessages, ...this.data.messageList],
      });

      // 检查是否获取到的消息数量小于 pageSize
      if (data.chatList.length < this.data.pageSize) {
        this.setData({ canLoadMore: false }); // 设置标志位，表示不能继续加载
      }

      wx.setNavigationBarTitle({
        title: data.seNickname,
      });
    }
  },

  handleMessage(result) {
    const message = JSON.parse(result);
    const newMessage = {
      content: message.content,
      createTime: new Date().toISOString(), // ISO 格式，不会有问题
      sender: message.sender,
      receiver: message.receiver,
      type: message.type,
    };

    const formattedMessage = {
      id: Date.now(),
      content: newMessage.content,
      time: this.formatTime(newMessage.createTime), // 修复日期格式
      showTime: false,
      isSelf: false,
    };
    this.setData({
      messageList: [...this.data.messageList, formattedMessage],
      inputValue: "",
    });
    this.scrollToBottom();
  },

  formatMessageList(chatList) {
    return chatList.map((msg, index, array) => {
      const showTime = this.shouldShowTime(msg, array[index - 1]);
      const isSelf = msg.sender !== this.data.receiverId;

      return {
        id: msg.id,
        content: msg.content,
        time: this.formatTime(msg.createTime), // 修复日期格式
        showTime: showTime,
        isSelf: isSelf,
      };
    });
  },

  shouldShowTime(currentMsg, prevMsg) {
    if (!prevMsg) return true;
    const currentTime = new Date(
      currentMsg.createTime.replace(" ", "T")
    ).getTime(); // 修复日期格式
    const prevTime = new Date(prevMsg.createTime.replace(" ", "T")).getTime(); // 修复日期格式
    return currentTime - prevTime > 5 * 60 * 1000;
  },

  formatTime(timeStr) {
    const fixedTimeStr = timeStr.replace(" ", "T"); // 替换空格为 T
    const date = new Date(fixedTimeStr);
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${hours}:${minutes}`;
  },

  async sendMessage() {
    if (!this.data.inputValue.trim()) return;
    const newMessage = {
      messageType: "message",
      content: this.data.inputValue,
      createTime: new Date().toISOString(), // ISO 格式，不会有问题
      sender: this.data.userInfo.id,
      receiver: this.data.secondUser.id,
      avatar: this.data.userInfo.avatar,
      type: 0,
      sendFailed: false,
    };
    const formattedMessage = {
      id: Date.now(),
      content: newMessage.content,
      time: this.formatTime(newMessage.createTime), // 修复日期格式
      showTime: true,
      isSelf: true,
      sendFailed: false,
    };

    this.setData({
      messageList: [...this.data.messageList, formattedMessage],
      inputValue: "",
    });
    this.scrollToBottom();

    try {
      app.sendMessage(
        JSON.stringify(newMessage),
        () => {},
        () => {
          const messageList = this.data.messageList.map((msg) => {
            if (msg.id === formattedMessage.id) {
              return { ...msg, sendFailed: true };
            }
            return msg;
          });
          this.setData({ messageList });
        }
      );
    } catch (error) {
      console.error("发送消息失败：", error);
    }
  },

  onInput(e) {
    this.setData({
      inputValue: e.detail.value,
    });
  },

  scrollToBottom() {
    console.log("返回底部");

    setTimeout(() => {
      const lastMessageId =
        this.data.messageList.length > 0
          ? this.data.messageList[this.data.messageList.length - 1].id
          : null;
      if (lastMessageId) {
        console.log(lastMessageId);

        wx.createSelectorQuery()
          .select(`#message-${lastMessageId}`)
          .boundingClientRect((rect) => {
            console.log(rect);

            if (rect) {
              console.log(rect.top + this.data.scrollTop);

              this.setData({
                scrollTop: rect.top + this.data.scrollTop,
              });
              console.log(this.data.scrollTop);
            }
          })
          .exec();
      }
    }, 50);
  },

  resendMessage(e) {
    const messageId = e.currentTarget.dataset.id;
    const message = this.data.messageList.find((msg) => msg.id === messageId);
    if (!message) return;

    app.sendMessage(
      JSON.stringify({
        messageType: "message",
        content: message.content,
        createTime: new Date().toISOString(), // ISO 格式，不会有问题
        sender: this.data.userInfo.id,
        receiver: this.data.secondUser.id,
        avatar: this.data.userInfo.avatar,
        type: 0,
      }),
      () => {
        const messageList = this.data.messageList.map((msg) => {
          if (msg.id === messageId) {
            return { ...msg, sendFailed: false };
          }
          return msg;
        });
        this.setData({ messageList });
      },
      () => {}
    );
  },
  async onScrollToUpper() {
    if (!this.data.canLoadMore) return; // 如果不能加载更多，直接返回
    this.setData({ page: this.data.page + 1 }); // 增加页码
    await this.getChatDetail({ id: this.data.receiverId }); // 重新获取聊天详情
  },

  // 开始语音输入
  startVoiceInput() {
    const options = {
      duration: 10000, // 录音时长，单位 ms
      sampleRate: 44100, // 采样率
      numberOfChannels: 1, // 声道数
      encodeBitRate: 192000, // 编码码率
      format: "mp3", // 音频格式，可选 'aac' 或 'mp3'
    };
    this.recorderManager.start(options); // 开始录音
  },

  // 发送语音消息
  sendVoiceMessage(tempFilePath) {
    console.log("发送语音消息");

    // 构造语音消息对象
    const newMessage = {
      messageType: "voice", // 消息类型为语音
      content: tempFilePath, // 语音文件路径
      createTime: new Date().toISOString(), // 消息创建时间
      sender: this.data.userInfo.id, // 发送者 ID
      receiver: this.data.secondUser.id, // 接收者 ID
      avatar: this.data.userInfo.avatar, // 发送者头像
      type: 1, // 语音类型
      sendFailed: false, // 发送是否失败
    };

    // 这里可以添加发送语音消息的逻辑
    // 例如：将 newMessage 发送到服务器或更新本地消息列表
    // this.sendMessageToServer(newMessage);
    // this.updateLocalMessageList(newMessage);

    console.log("语音消息对象：", newMessage);
  },

  // 停止录音（如果需要手动停止）
  stopVoiceInput() {
    this.recorderManager.stop();
  },

  toggleVoiceInput() {
    this.setData({ isVoiceInput: !this.data.isVoiceInput, inputValue: "" }); // 切换语音输入状态
  },

  onVoiceStart() {
    this.setData({ isCancelAreaVisible: false }); // 隐藏取消区域
    this.startVoiceInput(); // 开始录音
  },

  onVoiceEnd() {
    this.stopVoiceInput(); // 停止录音
    if (!this.data.isCancelAreaVisible) {
      this.sendVoiceMessage(this.tempFilePath); // 发送语音消息
    }
    this.setData({ isVoiceInput: false, isCancelAreaVisible: false }); // 退出语音输入状态
  },

  onVoiceMove(e) {
    const touchY = e.touches[0].clientY; // 获取触摸点的 Y 坐标
    const touchX = e.touches[0].clientX; // 获取触摸点的 X 坐标
    const cancelAreaX = 50; // 取消区域的 X 坐标（根据实际情况调整）
    const cancelAreaY = 100; // 取消区域的 Y 坐标（根据实际情况调整）

    // 判断是否滑动到取消区域
    if (touchX < cancelAreaX && touchY < cancelAreaY) {
      this.setData({ isCancelAreaVisible: true }); // 显示取消区域
    } else {
      this.setData({ isCancelAreaVisible: false }); // 隐藏取消区域
    }
  },
});
